<?php
namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Mockery\Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\RequestBackController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CheckController;
use App\Http\Controllers\v1\PurviewController;


class RecordController extends Controller
{
    ///案件归档
    public function CaseRecord($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['CaseId']))
        {
            return RequestBackController::Structure(502);
        }
        $case=DB::table('yl_case')->select('case_id','litigants_id','case_type_id','case_executor_id','case_title')->where('case_id',$pos['CaseId'])->first();
        $case->record_time=time();
        $case=(Array)$case;
        DB::table('yl_record')->insert($case);
        return RequestBackController::Structure(101);
    }


    ///新建(修改)归档
    public function AdditionalRecord($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['Litigants','CaseTitle','CaseTypeId','CaseExecutorId']))
        {
            return RequestBackController::Structure(502);
        }
        $Litigants=json_decode($pos['Litigants'],true);
        $LitigantsId='';
        if(is_array($Litigants))
        {
            $LitigantsId=$this->Litigants($Litigants);
        }
        if(isset($pos['RecordId'])&&!empty($pos['RecordId']))
        {
            $case=[
                'case_title'=>$pos['CaseTitle'],
                'case_type_id'=>$pos['CaseTypeId'],
                'case_executor_id'=>$pos['CaseExecutorId'],
                'litigants_id'=>$LitigantsId
            ];
            DB::table('yl_record')->where('case_id','')->where('record_id',$pos['RecordId'])->update($case);
        }
        else
        {
            $case=[
                'case_title'=>$pos['CaseTitle'],
                'case_type_id'=>$pos['CaseTypeId'],
                'case_executor_id'=>$pos['CaseExecutorId'],
                'litigants_id'=>$LitigantsId
            ];
            DB::table('yl_record')->insert($case);
        }

        return RequestBackController::Structure(101);
    }


    ///非案件归档删除
    public function DeleteRecord($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['RecordId']))
        {
            return RequestBackController::Structure(502);
        }
        $r=DB::table('yl_record')->where('case_id','')->where('record_id',$pos['RecordId'])->delete();
		if($r)
			return RequestBackController::Structure(101);
		else
			return RequestBackController::Structure(503);
    }


    ///归档列表
    public function RecordList($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId']))
        {
            return RequestBackController::Structure(502);
        }
		$Purview = new PurviewController();
		$UserPurview = $Purview->PurviewVerdict($request,$pos['UserId']);
		$page=isset($pos['page'])&&!empty($pos['page'])&&$pos['page']>=1?$pos['page']-1:0;
		$pageSize=isset($pos['pageSize'])&&!empty($pos['pageSize'])&&$pos['pageSize']>=1?$pos['pageSize']:10;
		$offset = $page * $pageSize;
		
		if($UserPurview=='None')
		{
			return RequestBackController::Structure(203);
		}
		$quest=DB::table('yl_record as r')->join('yl_case as c','c.case_id','r.case_id')
		->select(
		'r.record_id as RecordId',
		'r.record_time as RecordTime',
		'r.case_title as CaseTitle',
		'r.case_id as CaseId',
		'r.case_type_id as CaseTypeId',
		'r.case_executor_id as CaseExecutorId',
		'r.litigants_id as LitigantsId'
		);
		if(isset($pos['SearchWord'])&&!empty($pos['SearchWord']))
		{
			$LitigantsSeachRes=DB::table('yl_litigants')
				->select('litigant_id')
				->where('litigant_name','like','%'.$pos['SearchWord'].'%')
				->get()
				->map(function ($val){$val = (array)$val;return $val;})
				->keyBy(function($item){return $item['litigant_id'];})
				->toArray();
			$UserSeachRes=DB::table('yl_user')
				->select('user_id')
				->where('user_name','like','%'.$pos['SearchWord'].'%')
				->get()
				->map(function ($val){$val = (array)$val;return $val;})
				->keyBy(function($item){return $item['user_id'];})
				->toArray();
			$quest=$quest->where(function($quest) use ($pos,$LitigantsSeachRes,$UserSeachRes){
				$quest->where('c.case_title','like','%'.$pos['SearchWord'].'%');
				foreach($LitigantsSeachRes as $LK=>$LV)
				{
					$quest=$quest->orwhere(function($quest) use ($LV){
						$quest=$quest->whereRaw("FIND_IN_SET(".$LV['litigant_id'].",r.litigants_id)");
					});
				}				
				foreach($UserSeachRes as $UK=>$UV)
				{
					$quest=$quest->orwhere(function($quest) use ($UV){
						$quest=$quest->whereRaw("FIND_IN_SET(".$UV['user_id'].",r.case_executor_id)");
					});
				}
			});
		}
		if($UserPurview=='Personal')
		{
			$quest=$quest->whereRaw("FIND_IN_SET($pos[UserId],c.case_member_id) or FIND_IN_SET($pos[UserId],c.case_from_id) or FIND_IN_SET($pos[UserId],c.case_executor_id)");
		}
		if(isset($pos['CaseTypeId'])&&!empty($pos['CaseTypeId']))
		{
			$quest=$quest->where('c.case_type_id',$pos['CaseTypeId']);
		}
		
		$quest=$quest->orderBy('r.record_time','desc');
		$count=$quest->count();
		$quest->offset($offset)->limit($pageSize);
		$sum_page = ceil($count/$pageSize);
		$res=$quest->get()->map(function ($val){
			$val = (array)$val;$val['RecordTime']=date('Y-m-d',$val['RecordTime']);
			$val['Executors']=[];$val['Litigants']=[];return $val;
		})
		->keyBy(function($item){return $item['CaseId'];})->toArray();
		$case_executor_id=[];
		$litigants_id=[];
		$case_executor=[];
		foreach($res as $k=>$v)
		{
			$temp_CaseExecutorId=explode(',',$v['CaseExecutorId']);
			if(is_array($v['CaseExecutorId']))
			{
				foreach($temp_CaseExecutorId as $key=>$val)
				{
					$case_executor[$k][$val]=$val;
					$case_executor_id[$val]=$val;
				}
			}
			else
			{
				$case_executor[$k][$v['CaseExecutorId']]=$v['CaseExecutorId'];
				$case_executor_id[$v['CaseExecutorId']]=$v['CaseExecutorId'];
			}
			$temp_LitigantsId=explode(',',$v['LitigantsId']);
			if(is_array($temp_LitigantsId))
			{
				foreach($temp_LitigantsId as $key=>$val)
				{
					$litigants_id[$val]=$val;
				}
			}
			else
			{
				$litigants_id[$v['LitigantsId']]=$v['LitigantsId'];
			}
		}
		$litigants_res=DB::table('yl_litigants')
		->whereIn('litigant_id',$litigants_id)
		->get()
		->map(function ($val){$val = (array)$val;return $val;})
		->keyBy(function($item){return $item['litigant_id'];})
		->toArray();
		foreach($litigants_res as $k=>$v)
		{
			$res[$v['case_id']]['Litigants'][]=[
			'LitigantId'=>$v['litigant_id'],
			'LitigantName'=>$v['litigant_name'],
			];
		}
		$user_res=DB::table('yl_user')
		->whereIn('user_id',$case_executor_id)
		->get()
		->map(function ($val){$val = (array)$val;return $val;})
		->keyBy(function($item){return $item['user_id'];})
		->toArray();
		
		foreach($case_executor as $k=>$v)
		{
			foreach($v as $key=>$val)
			{
				$res[$k]['Executors'][]=[
				'UserId'=>$user_res[$val]['user_id'],
				'UserName'=>$user_res[$val]['user_name'],
				'UserImg'=>$user_res[$val]['user_img'],
				];
			}
		}
		$res=array_values($res);
		$list['List']=$res;
		$list['Count']=$count;
		if(!empty($res))
			return RequestBackController::Structure(101,$list);
		else
			return RequestBackController::Structure(504);
		
    }

    ///新增当事人
    protected function Litigants($Arr)
    {
        $LitigantsId=null;
        $temp=null;
        foreach($Arr as $k=>$v)
        {
            $temp=[
                'litigation_status_id'=>$v['LitigationStatusId'],
                'litigant_name'=>$v['LitigantName'],
                'litigant_mobile'=>$v['LitigantMobile'],
                'litigant_type_id'=>$v['LitigantTypeId'],
                'litigant_id_card'=>$v['LitigantIdCard'],
            ];
            if(isset($v['LitigantId'])&&!empty($v['LitigantId']))
            {
                DB::table('yl_litigats')->where('litigant_id',$v['LitigantId'])->update($temp);
                $Lid=$v['LitigantId'];
            }
            else
            {
                $Lid=DB::table('yl_litigats')->insertGetId($temp);
            }
            if(!empty($LitigantsId))
            {
                $LitigantsId.=','.$Lid;
            }
            else
                $LitigantsId=$Lid;
        }
        return $LitigantsId;
    }
}